import re


from rest_framework import serializers
from users.models import User



class RegisterCreateSerializer(serializers.ModelSerializer):


    # write_only是只用于反序列化器,
    password2 = serializers.CharField(label="校验密码", write_only=True)
    sms_code = serializers.CharField(write_only=True, label="短信验证码", max_length=6,min_length=6)
    allow = serializers.CharField(write_only=True, label="是否同意协议")

    # token只是在序列化的时候会使用,所以只是需要读,设置为read_only就好
    token = serializers.CharField(label="令牌token", read_only=True)

    class Meta:

        model = User
        # 用户名, 密码, 短信验证码, 是否同意协议, 手机号, 确认密码
        fields = ["username", "password", "password2", "sms_code", "allow", "mobile", "id", "token"]

    def validate_mobile(self, value):

        if not re.match(r"1[3-9]\d{9}", value):
            raise serializers.ValidationError("手机号的格式不正确")
        return value

    def validated_allow(self, value):

        if value != "true":
            raise serializers.ValidationError("您还未同意协议")
        return value

    def validate(self, attrs):
        password2 = attrs.get("password2")
        password = attrs["password"]
        # password = attrs.get("password")
        mobile = attrs.get("mobile")

        sms_code = attrs.get("sms_code")

        if password != password2:
            raise serializers.ValidationError("密码不一致")

        # 比较手机验证码
        from django_redis import get_redis_connection
        redis_conn = get_redis_connection("code")
        redis_text = redis_conn.get("sms_%s" % mobile)
        if redis_text is None:
            raise serializers.ValidationError("短信验证码已经过期了")

        if sms_code != redis_text.decode():
            raise serializers.ValidationError("短信验证码不正确")

        return attrs

    def create(self, validated_data):

        del validated_data["password2"]
        del validated_data["sms_code"]
        del validated_data["allow"]

        user = super().create(validated_data)

        # 密码是明文显示,所以得要改成密文
        user.set_password(validated_data["password"])
        user.save()


        # 手动创建一个令牌,在创建账户以后就直接返回登录
        from rest_framework_jwt.settings import api_settings

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        user.token = token

        return user




